# -*- coding: utf-8 -*-
from match import Extractor
import regex as re
from storage.digit_util import *

def get_number(prefix, suffix, text):
    num_reg_pattern = "([亿万千百十零两一二三四五六七八九点\\.0123456789]{1,40})"
    pattern = re.compile(prefix + num_reg_pattern + suffix, re.S)
    result_list = []
    number_str_list = pattern.findall(text)
    for number_str in number_str_list:
        number_str = number_str.replace("两","二")
        if(number_str == "万"):
            continue
        cn_num = True
        arabic_num = True
        for char in number_str:
            if ord(char) > 512:
                arabic_num = False
            else:
                cn_num = False
        if arabic_num:
            try:
                result_list.append(float(number_str))
            except:
                print("bad number" + number_str)
        if cn_num:
            result_list.append(float(takeChineseNumberFromString(number_str)["replacedText"]))
        if not cn_num and not arabic_num and number_str.endswith("亿"):
            try:
                result_list.append(float(number_str[:-1]) * 100000000)
            except:
                print("bad number" + number_str)
        if not cn_num and not arabic_num and number_str.endswith("万"):
            try:
                result_list.append(float(number_str[:-1]) * 10000)
            except:
                print("bad number" + number_str)
    return result_list


class WeiXianJiaShiExtractor(Extractor):

    # 该辩护要点仅仅适用于盗窃
    @staticmethod
    def is_my_job(file_path):
        return "危险驾驶罪" in file_path

    @staticmethod
    def extract(text):
        result = {}
        alcohol_count_list = get_number("","[^亿万千百十零一二三四五六七八九点\\.0123456789]{0,2}[mM][gG]",text)
        if(len(alcohol_count_list)==0):
            result["血液酒精浓度"] = 0
        else:
            result["血液酒精浓度"] = max(alcohol_count_list)
        money_count_list = get_number("损失[^亿万千百十零一二三四五六七八九点\\.0123456789]{0,5}", "元", text)
        if (len(money_count_list) == 0):
            result["财产损失"] = 0
        else:
            result["财产损失"] = max(money_count_list)
        result["无证驾驶"] = "无证驾驶" in text
        result["曾被处罚"] = re.search("曾因.{0,20}(罪|犯|处罚|判处)", text) is not None
        damage_level_list = get_number("轻伤","级",text)
        if(len(damage_level_list)==0):
            result["轻伤等级"] = 0
        else:
            result["轻伤等级"] = int(max(damage_level_list))
        return result


if __name__ == '__main__':
    print(WeiXianJiaShiExtractor.extract("血液酒精浓度12.7mg/毫升，轻伤二级，损失共计200元，并驾车逃逸。曾因杀人被判处有期徒刑5年。无证驾驶，驾车逃逸。"))
    from match import *
    from storage import *
    import json
    import os

    data_util = DataUtil("../data/危险驾驶罪")
    extractors = [WeiXianJiaShiExtractor]

    file_path, text = data_util.next_line()
    count_dict = {}
    count_key_list = ["血液酒精浓度", "财产损失", "无证驾驶", "曾被处罚", "轻伤等级"]
    while text:
        text_json = json.loads(text)
        if file_path not in count_dict:
            count_dict[file_path] = {"count": 0}
        for extractor in extractors:
            if extractor.is_my_job(file_path):
                result = extractor.extract("\n".join(text_json["content"]))
                for key in count_key_list:
                    result_value = result[key]
                    if (type(result_value) == int or type(result_value) == float):
                        if key in count_dict[file_path]:
                            count_dict[file_path][key] = count_dict[file_path][key] + result_value
                        else:
                            count_dict[file_path][key] = result_value
                    else:
                        if key in count_dict[file_path]:
                            if result_value in count_dict[file_path][key]:
                                count_dict[file_path][key][result_value] = count_dict[file_path][key][result_value] + 1
                            else:
                                count_dict[file_path][key][result_value] = 1
                        else:
                            count_dict[file_path][key] = {}
                            count_dict[file_path][key][result_value] = 1
        count_dict[file_path]["count"] = count_dict[file_path]["count"] + 1
        file_path, text = data_util.next_line()
    for key in count_dict:
        print(key)
        count = count_dict[key]["count"]
        for ckey in count_key_list:
            ckey_result = count_dict[key][ckey]
            if (type(ckey_result) == int or type(ckey_result) == float):
                print(str(ckey) + ":%f" % (ckey_result / float(count)))
            else:
                for cckey in ckey_result:
                    print(str(ckey) + "_" + str(cckey) + ":%f" % (ckey_result[cckey] / float(count)))
    print(count_dict)
